package com.demo.security.cloud.service.impl;

import com.demo.security.cloud.entity.TUser;
import com.demo.security.cloud.entity.dto.PermissionDto;
import com.demo.security.cloud.service.ITPermissionService;
import com.demo.security.cloud.service.ITUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(SpringDataUserDetailsService.class);

    @Autowired
    private ITUserService userService;

    @Autowired
    private ITPermissionService permissionService;

    /**
     * 定义用户信息服务（查询用户信息）
     * 用户信息服务可以查数据库，也可以内存的方式
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        logger.info("loadUserByUsername username={}", username);
        TUser user = userService.getUserByUserName(username);
        if (user == null){
            return null;
        }

        // 获取权限
        List<PermissionDto> permissionDtoList = permissionService.getPermissionsByUserId(user.getId());

        List<String> as = new ArrayList<>();
        permissionDtoList.forEach(p -> {
            as.add(p.getCode());
        });
        String[] asArr = new String[as.size()];
        as.toArray(asArr);
        logger.info("read userinfo username={} password={}", user.getUserName(), user.getPassword());
        return User.withUsername(user.getUserName()).password(user.getPassword()).authorities(asArr).build();
    }
}
